package comAPIdlw.service;
import com.alibaba.fastjson.JSONObject;
import comAPIdlw.Constants;
import comAPIdlw.bean.BestBlockHash;
import comAPIdlw.request.HttpUtils;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: dlw
 * @QQ : 1595507337
 * * @Date: 2021/12/16 21:18
 * @desc:该类用于实现调用实现比特币客户端GetBestBlockHash的rpc的功能
 */
public class GetBestBlockHashService {

       public  String GetBestBlockHash(){
           //准备用户身份信息  拼接
          String author = Constants.BITCOIN_RPC_USER +":"+ Constants.BITCOIN_RPC_PWD;
          //进行64编码
           Base64.Encoder encoder=Base64.getEncoder();
           String authorBase64 = encoder.encodeToString(author.getBytes());


           Map<String,String> header = new HashMap<>();
           //添加
           header.put("ContentType","application/json");
           header.put("Authorization","Basic "+authorBase64);

           //  json rpc请求格式
           Map<String,Object> data =new HashMap<>();
           data.put("id",1001);
           data.put("method","getbestblockhash");
           data.put("params",null);
           data.put("json_rpc","2.0");
           //data 数据转换成byte[]数组 JSONObject 阿里巴巴
           //byte[] dataBytes = JSONObject.toJSONBytes(data);
        byte[] dataBytes = JSONObject.toJSONBytes(data);
        //result输出 格式  id 1001   result  xxxx  error null
           //准备请求头信息
           String result = HttpUtils.post(Constants.BITCOIN_RPC_URL, header, dataBytes);
           BestBlockHash bestBlockHash = JSONObject.parseObject(result, BestBlockHash.class);

           return  bestBlockHash.result;

       }

}
